#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "Mutex.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include "Log.hpp"
using namespace ThreadModule;
using namespace LogModule;
using namespace CondModule;
using namespace MutexModule;

namespace ThreadPoolModule
{

    static const int gnum = 5;
    template <class T>
    class ThreadPool
    {
    private:
        void WakeUpOneThread()
        {
            _cond.Signal();
            LOG(LogLevel::INFO) << "唤醒一个休眠线程";
        }

        void WakeUpAllThreads()
        {
            LockGurd lockguard(_mutex);
            if (_sleepernum)
                _cond.Broadcast();
            LOG(LogLevel::INFO) << "唤醒所有休眠线程";
        }
        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;
            for (auto &thread : _threads)
            {
                thread.Start();
                // LOG(LogLevel::INFO) << "start new thread success: " << thread.Name();
            }
        }

        ThreadPool(int num = gnum)
            : _num(num), _isrunning(false), _sleepernum(0)
        {
            for (int i = 0; i < _num; i++)
            {
                _threads.emplace_back([this]()
                                      { HanderTask(); });
            }
        }

        // 禁止拷贝和赋值
        ThreadPool(const ThreadPool &) = delete;
        ThreadPool &operator=(const ThreadPool &) = delete;

    public:
        // 设计为静态成员函数可以直接访问静态成员变量
        static ThreadPool<T> *GetInstance()
        {
            if (inc == nullptr)
            {
                // 加锁
                // 由于产生单例时并没有实例化对象，因此访问不了非成员变量锁，需要一个静态成员变量锁
                LockGurd lockguard(_lock);
                LOG(LogLevel::DEBUG) << "获取单例....";

                // 1、双重if判断，降低锁冲突的概率，提高性能
                // 2、使用互斥锁，保证多线程访问线程池时，线程安全
                if (inc == nullptr)
                {
                    LOG(LogLevel::DEBUG) << "首次使用单例, 创建之....";
                    inc = new ThreadPool<T>(); // 创建线程池
                    inc->Start();
                }
            }
            return inc;
        }

        void Stop()
        {
            if (!_isrunning)
                return;
            _isrunning = false;

            // 唤醒所有的线层
            WakeUpAllThreads();
        }

        void Join()
        {
            for (auto &thread : _threads)
            {
                thread.Join();
            }
        }

        void HanderTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                T t;
                // 加锁
                {
                    LockGurd lockguard(_mutex);
                    // 判断线程休眠：任务队列为空&&_isrunning为true
                    while (_taskq.empty() && _isrunning)
                    {
                        _sleepernum++;
                        _cond.Wait(_mutex);
                        _sleepernum--;
                    }
                    // 判断线程池是否退出：任务队列为空&&_isrunning为false
                    if (_taskq.empty() && !_isrunning)
                    {
                        LOG(LogLevel::INFO) << name << "线程退出了&&任务队列为空";
                        break;
                    }

                    // 一定有任务
                    t = _taskq.front();
                    _taskq.pop();
                }
                t(); // 处理任务属于线程私有，不需要在临界区处理
            }
        }

        bool Enqueue(const T &in)
        {
            if (_isrunning)
            {
                // 加锁
                LockGurd lockguard(_mutex);
                _taskq.push(in);
                if (_threads.size() == _sleepernum)
                    WakeUpOneThread();
                return true;
            }
            return false;
        }

    private:
        std::vector<Thread> _threads;
        int _num;             // 线程池中线程个数
        std::queue<T> _taskq; // 任务队列；
        Cond _cond;
        Mutex _mutex;
        bool _isrunning; // 用于判断线程池退出
        int _sleepernum; // 休眠线程个数

        static ThreadPool<T> *inc; // 单例指针
        static Mutex _lock;
    };
    // 静态成员在类外初始化
    template <class T>
    ThreadPool<T> *ThreadPool<T>::inc = nullptr;

    template <class T>
    Mutex ThreadPool<T>::_lock;
}